package com.briup.estore.service.Impl;


import com.briup.estore.bean.Book;
import com.briup.estore.bean.ShopCart;
import com.briup.estore.bean.ShopCartExample;
import com.briup.estore.bean.extend.ShopCartExtend;
import com.briup.estore.dao.BookMapper;
import com.briup.estore.dao.ShopCartMapper;
import com.briup.estore.dao.extend.ShopCartExtendMapper;
import com.briup.estore.service.ShopCartService;
import com.briup.estore.util.MyBatisSqlSessionFactory;
import org.apache.ibatis.session.SqlSession;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;

public class ShopCartServiceImpl implements ShopCartService {
    private ShopCartMapper shopcartMapper;
    private BookMapper bookMapper;
    private ShopCartExtendMapper shopCartExtendMapper;
    {
        SqlSession sqlSession = null;
        try {
            sqlSession = MyBatisSqlSessionFactory.openSession();
            shopcartMapper=sqlSession.getMapper(ShopCartMapper.class);
            bookMapper=sqlSession.getMapper(BookMapper.class);
            shopCartExtendMapper=sqlSession.getMapper(ShopCartExtendMapper.class);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    @Override
    public void addBook2ShopCart(ShopCart shopCart) {
        //如果相同的userId购买了相同的bookId，那么做更新操作
        //根据userId和bookId进行查询
        ShopCartExample example=new ShopCartExample();
        example.createCriteria().andUserIdEqualTo(shopCart.getUserId()).andBookIdEqualTo(shopCart.getBookId());
        List<ShopCart> list = shopcartMapper.selectByExample(example);
        Book book =bookMapper.selectByPrimaryKey(shopCart.getBookId());
        BigDecimal b1=new BigDecimal(book.getPrice());
        BigDecimal b2=new BigDecimal(shopCart.getNum());
        double total=b1.multiply(b2).setScale(2).doubleValue();
        if(list ==null||list.size()==0){
            //根据bookId查询book对象


            if(shopCart.getTotal()==null){
                shopCart.setTotal(total);
            }
            shopcartMapper.insert(shopCart);
        }else{
            //数据库里查出来的数据
            ShopCart sc=list.get(0);
            //用传入的数据，加上数据库里有的数据，做更新
            double newTotal=total;
            ShopCart s1=new ShopCart();
            s1.setId(sc.getId());
            s1.setNum(sc.getNum()+shopCart.getNum());
            s1.setTotal(sc.getTotal()+total);
            shopcartMapper.updateByPrimaryKeySelective(s1);
        }
    }

    @Override
    public List<ShopCart> findShopCartByUserId(Integer userId) {
        //按条件查询，使用example
        ShopCartExample example=new ShopCartExample();
        example.createCriteria().andUserIdEqualTo(userId);
        return shopcartMapper.selectByExample(example);
    }

    @Override
    public List<ShopCartExtend> findShopCartDetailByUserId(Integer userid) {
        return shopCartExtendMapper.findAllByUserId(userid);
    }


}
